﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vcare.Models;
using Vcare.DAL;
using Vcare.ViewModels;
using System.Web.Security;

namespace Vcare.Controllers
{
    public class UserInfoController : Controller
    {
        private VcareContext db = new VcareContext();

        public Guid? CurrentUserID { get; set; }
        //
        // GET: /UserInfo/

        public ActionResult Index()
        {
          if (this.CurrentUserID==null)
          {
            this.CurrentUserID = (Guid)Membership.GetUser().ProviderUserKey;
          }
          Guid thisID = this.CurrentUserID ?? (Guid)Membership.GetUser().ProviderUserKey;
          Guid currentUserID = thisID;
          UserInfo userInfo = db.UserInfo.Where(m => m.UserID == currentUserID).FirstOrDefault();
          bool callCentreAdministrator = db.Authority.Find(userInfo.AuthorityID).Level == 2;
          IEnumerable<UserInfo> userinfo;

          if (callCentreAdministrator)
          {
          userinfo = db.UserInfo
            .Include(u => u.Authority)
            .Include(u => u.CallCentre)
            .Where(m => m.Authority.ShowCat == "C" && m.CallCentreID==userInfo.CallCentreID)
            .ToList();
          }
          else
          {
            userinfo = db.UserInfo
            .Include(u => u.Authority)
            .Include(u => u.CallCentre)
            .ToList();
          }

            return View(userinfo.ToList());
        }

        //
        // GET: /UserInfo/Details/5

        public ActionResult Details(int id = 0)
        {
            UserInfo userinfo = db.UserInfo.Find(id);
            if (userinfo == null)
            {
                return HttpNotFound();
            }
            return View(userinfo);
        }

        //
        // GET: /UserInfo/Create

        public ActionResult Create()
        {
          ViewModelUserInfo ViewModel = new ViewModelUserInfo();
          Guid currentUserID=(Guid)Membership.GetUser().ProviderUserKey;
          ViewModel.UserInfo = db.UserInfo.Where(m => m.UserID == currentUserID).FirstOrDefault();

          ViewModel.SystemAdministrator = db.Authority.Find(ViewModel.UserInfo.AuthorityID).Level == 1;
          ViewModel.CallCentreAdministrator = db.Authority.Find(ViewModel.UserInfo.AuthorityID).Level == 2;
          if (ViewModel.CallCentreAdministrator)
          {
            int? ccID=db.UserInfo.Where(m => m.UserID==currentUserID).FirstOrDefault().CallCentreID ?? 0;
            ViewModel.CallCentre=db.CallCentres.Where(cc => cc.CallCentreID==ccID).FirstOrDefault() ;
          }
          else
          {
            ViewBag.CallCentreID = new SelectList(db.CallCentres, "CallCentreID", "CallCentre");
          }
          if (ViewModel.CallCentreAdministrator)
          {
            ViewBag.AuthorityID = new SelectList(db.Authority.Where(m => m.ShowCat=="C"), "AuthorityID", "Description");
          }
          else
          {
            ViewBag.AuthorityID = new SelectList(db.Authority, "AuthorityID", "Description");
          }
          ViewModel.UserInfo = new UserInfo();
          return View(ViewModel);
        }

        //
        // POST: /UserInfo/Create

        [HttpPost]
        public ActionResult Create(ViewModelUserInfo ViewModel)
        {
          if (ViewModel.CallCentreID==null)
          {
            ViewModel.UserInfo.CallCentreID = null;
          }
            if (ModelState.IsValid)
            {
              ViewModel.UserInfo.AuthorityID = ViewModel.AuthorityID;
              ViewModel.UserInfo.CallCentreID = ViewModel.CallCentreID;
              
              MembershipCreateStatus createStatus;
              MembershipUser user= Membership.Provider.CreateUser(ViewModel.UserName, ViewModel.Password, "karl@dunsmoremarketing.co.uk", passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);

              if (createStatus == MembershipCreateStatus.Success)
              {
                FormsAuthentication.SetAuthCookie(ViewModel.UserName, createPersistentCookie: false);
                Guid newID = new Guid(user.ProviderUserKey.ToString());
                ViewModel.UserInfo.UserID = newID;
                if (ViewModel.UserInfo.CallCentreID==0)
                {
                  ViewModel.UserInfo.CallCentreID = ViewModel.CallCentre.CallCentreID;
                }
                db.UserInfo.Add(ViewModel.UserInfo);
                db.SaveChanges();
                // Assign correct Role
                Roles.AddUserToRole(ViewModel.UserName, db.Authority.Find(ViewModel.AuthorityID).RoleDescription);

                AccountController accountController = new AccountController();
                LoginModel loginModel=new LoginModel();
                loginModel.UserName=(string)Session["username"];
                loginModel.Password=(string)Session["password"];
                accountController.Login(loginModel,"UserInfo/Index");
                return RedirectToAction("Index");
              }
              else
              {
                return RedirectToAction("Create");
              }

            }
            return RedirectToAction("Index");
        }

        //
        // GET: /UserInfo/Edit/5

        public ActionResult Edit(int id = 0)
        {
            UserInfo userinfo = db.UserInfo.Find(id);
            if (userinfo == null)
            {
                return HttpNotFound();
            }
            Guid newID = (Guid)Membership.GetUser().ProviderUserKey;
            int? callCentreid = db.CallCentres.Find(db.UserInfo.Where(m => m.UserID == newID).FirstOrDefault().CallCentreID).CallCentreID;
            if (callCentreid!=null)
            {
              userinfo.CallCentre = db.CallCentres.Find(callCentreid);              
            }
            ViewBag.CallCentreID = new SelectList(db.CallCentres, "CallCentreID", "CallCentre", userinfo.AuthorityID);
            ViewBag.AuthorityID = new SelectList(db.Authority, "AuthorityID", "Description", userinfo.AuthorityID);

            return View(userinfo);
        }

        //
        // POST: /UserInfo/Edit/5

        [HttpPost]
        public ActionResult Edit(UserInfo userinfo, int oldAuthorityID)
        {
            if (ModelState.IsValid)
            {
              Guid thisID = (Guid)Membership.GetUser().ProviderUserKey;
              userinfo.Authority = db.Authority.Find(userinfo.AuthorityID);
              userinfo.User.LastActivityDate = DateTime.Now;
              db.Entry(userinfo).State = EntityState.Modified;
              db.Entry(userinfo.User).State = EntityState.Modified;
              db.SaveChanges();
              // may have changed role
              if (userinfo.AuthorityID != oldAuthorityID)
              {
                Roles.RemoveUserFromRole(userinfo.User.UserName, db.Authority.Find(oldAuthorityID).RoleDescription);
                Roles.AddUserToRole(userinfo.User.UserName, db.Authority.Find(userinfo.AuthorityID).RoleDescription);
              }

               return RedirectToAction("Index");

            }
            ViewBag.AuthorityID = new SelectList(db.Authority, "AuthorityID", "Description", userinfo.AuthorityID);
            return View(userinfo);
        }

        //
        // GET: /UserInfo/Delete/5

        public ActionResult Delete(int id = 0)
        {
            UserInfo userinfo = db.UserInfo.Find(id);
            if (userinfo == null)
            {
                return HttpNotFound();
            }
            return View(userinfo);
        }

        //
        // POST: /UserInfo/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
          UserInfo userinfo = db.UserInfo.Find(id);
          string userName = userinfo.User.UserName;
          int authorityID = userinfo.AuthorityID;
          db.Users.Remove(userinfo.User);
          db.UserInfo.Remove(userinfo);
          Roles.RemoveUserFromRole(userName, db.Authority.Find(authorityID).RoleDescription);
          db.SaveChanges();
          return RedirectToAction("Index");
         }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}